import React,{useEffect,useState} from 'react'
import {getlist,check_active} from "../../api/index"
import { Tabs ,ProductCard, PullRefresh, List,} from 'react-vant'
import Son from '../../compontes/Son'
import {useDispatch,useSelector} from "react-redux"

import {RootDispatch} from "../../untils/index"
type Props = {}

const Home = (props: Props) => {
  
      // 模拟异步请求
async function getData(throwError:object) {
  // console.log(throwError);
  
  return new Promise<number[]>((resolve, reject) => {
    setTimeout(() => {
     
      resolve(Array.from({ length: 1 }, (_, i) => i))
    }, 2000)
  })
}

const [list, setList] = useState<any[]>([])
  const [finished, setFinished] = useState(false)

  const onLoadRefresh = async (isRefresh:any) => {
    const data = await getData(Object)
    console.log(typeof data);
    
    setList(v => {
      const newList = isRefresh ? data : [...v, ...data]
      if (newList.length >= 3) {
        setFinished(true)
      }
      return newList
    })
  }
  const onRefresh = async () => {
    setFinished(false)
    await onLoadRefresh(1)
  }
  const dispatch:RootDispatch=useDispatch()
  const data=useSelector((state:any)=>{
    return state.reducer.data
  })
  const childrenData=useSelector((state:any)=>{
    return state.reducer.childrenData
  })
  useEffect(()=>{
   dispatch(getlist())
  },[dispatch])
  // console.log(data,childrenData);
  let tab={childrenData}
  return (
  
       <Tabs onClickTab={(e)=>{dispatch(check_active(e.index))}} sticky>
        {data&&data.map((item:any,index:number) => (
          <Tabs.TabPane key={index} title={item.title}>
             <PullRefresh onRefresh={onRefresh}>
      {/* List 组件可以与 PullRefresh 组件结合使用，实现下拉刷新的效果 */}
      <List finished={finished} onLoad={onLoadRefresh} finishedText={"数据加载完了"}>
        {list.map((_, i) => (
           <Son {...tab} key={i}></Son>
         
        ))}
      </List>
    </PullRefresh>
  
         
          </Tabs.TabPane>
        ))}
      </Tabs>
  
  )
}

export default Home